<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Support\Facades\Cache;
use App\Services\SetUserPayCode\SetUserPayCode;
use App\Services\ResetUserPassword\ResetUserPassword;
use App\Services\SetUserPayCode\SetUserPayCodeRequest;
use App\Services\ResetUserPassword\ResetUserPasswordRequest;

class PasswordsController extends Controller
{
	public function reset()
	{
		$lock = Cache::lock('reset_password', 15);

		try {

			if (!$lock->get()) fail('请稍后重试');

			$request = app(ResetUserPasswordRequest::class);

			app(ResetUserPassword::class, [
				'user' => $request->getUser(),
				'password' => $request->password,
			])->reset();

		} finally {
			$lock->release();
		}

		return response(null, 204);
	}

	public function setPayCode()
	{
		$lock = Cache::lock('set_pay_code', 15);

		try {

			if (!$lock->get()) fail('请稍后重试');

			$request = app(SetUserPayCodeRequest::class);

			$user = $request->user();

			$captchaData = Cache::get($request->captcha_key);

			if (!$captchaData) {
				fail('图片验证码无效');
			}

			if (!hash_equals(strtolower($captchaData['code']), strtolower($request->captcha_code))) {
				Cache::forget($request->captcha_key);
				fail('图片验证码错误');
			}

			app(SetUserPayCode::class, [
				'user' => $user,
				'payCode' => $request->new_pay_code,
			])->set();

			Cache::forget($request->captcha_key);
			$user->resetPayCodeTry();

		} finally {
			$lock->release();
		}

		return response(null, 204);
	}
}
